"use client";

import { useState, useRef, useEffect } from "react";
import { Send, User, Bot, CornerDownLeft, HelpCircle } from "lucide-react";
import { AppItem } from "@/app/mockData"; // Assuming AppItem is exported

interface ChatMessage {
  id: string;
  text: string;
  sender: "user" | "ai";
  timestamp: Date;
}

interface ChatGPTSimulationProps {
  app: AppItem;
}

const ChatGPTSimulation = ({ app }: ChatGPTSimulationProps) => {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [inputValue, setInputValue] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const messagesEndRef = useRef<null | HTMLDivElement>(null);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  useEffect(scrollToBottom, [messages]);

  // Initial AI greeting message
  useEffect(() => {
    setMessages([
      {
        id: crypto.randomUUID(),
        text: `你好！我是 ${app.name}。今天我能为你做些什么？你可以试试问我：`, 
        sender: "ai",
        timestamp: new Date(),
      },
    ]);
  }, [app.name]);

  const handleSendMessage = async () => {
    if (inputValue.trim() === "") return;

    const userMessage: ChatMessage = {
      id: crypto.randomUUID(),
      text: inputValue,
      sender: "user",
      timestamp: new Date(),
    };
    setMessages((prevMessages) => [...prevMessages, userMessage]);
    setInputValue("");
    setIsLoading(true);

    // Simulate AI response
    setTimeout(() => {
      const aiResponse: ChatMessage = {
        id: crypto.randomUUID(),
        text: `这是针对“${userMessage.text}”的模拟回复。在实际应用中，这里会是 ${app.name} 生成的真实答复。例如，如果这是一个音乐应用，我可能会提供和弦进行或解释音乐理论。`, 
        sender: "ai",
        timestamp: new Date(),
      };
      setMessages((prevMessages) => [...prevMessages, aiResponse]);
      setIsLoading(false);
    }, 1500 + Math.random() * 1000);
  };

  const handleExamplePrompt = (prompt: string) => {
    setInputValue(prompt);
  };

  return (
    <div className="bg-gray-800 shadow-xl rounded-lg p-6 flex flex-col h-[600px] max-h-[70vh]">
      <div className="flex-grow overflow-y-auto mb-4 pr-2 space-y-4 custom-scrollbar">
        {messages.map((msg) => (
          <div
            key={msg.id}
            className={`flex items-end space-x-2 ${msg.sender === "user" ? "justify-end" : ""}`}>
            {msg.sender === "ai" && (
              <div className="flex-shrink-0 w-8 h-8 rounded-full bg-gradient-to-br from-purple-500 to-pink-500 flex items-center justify-center text-white">
                <Bot size={18} />
              </div>
            )}
            <div
              className={`max-w-[70%] p-3 rounded-xl shadow ${
                msg.sender === "user"
                  ? "bg-indigo-600 text-white rounded-br-none"
                  : "bg-gray-700 text-gray-200 rounded-bl-none"
              }`}>
              <p className="text-sm whitespace-pre-wrap">{msg.text}</p>
              <p className={`text-xs mt-1 ${msg.sender === "user" ? "text-indigo-200" : "text-gray-400"} text-right`}>
                {msg.timestamp.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
              </p>
            </div>
            {msg.sender === "user" && (
              <div className="flex-shrink-0 w-8 h-8 rounded-full bg-gray-600 flex items-center justify-center text-white">
                <User size={18} />
              </div>
            )}
          </div>
        ))}
        {isLoading && (
          <div className="flex items-end space-x-2">
            <div className="flex-shrink-0 w-8 h-8 rounded-full bg-gradient-to-br from-purple-500 to-pink-500 flex items-center justify-center text-white">
              <Bot size={18} />
            </div>
            <div className="max-w-[70%] p-3 rounded-xl shadow bg-gray-700 text-gray-200 rounded-bl-none">
              <div className="flex items-center space-x-1">
                <div className="w-2 h-2 bg-gray-400 rounded-full animate-pulse delay-75"></div>
                <div className="w-2 h-2 bg-gray-400 rounded-full animate-pulse delay-150"></div>
                <div className="w-2 h-2 bg-gray-400 rounded-full animate-pulse delay-225"></div>
              </div>
            </div>
          </div>
        )}
        <div ref={messagesEndRef} />
      </div>

      {app.chatPromptExamples && app.chatPromptExamples.length > 0 && (
        <div className="mb-3 flex flex-wrap gap-2">
          {app.chatPromptExamples.slice(0, 3).map((prompt, index) => (
            <button
              key={index}
              onClick={() => handleExamplePrompt(prompt)}
              className="px-3 py-1.5 text-xs bg-gray-700 hover:bg-gray-600 text-indigo-300 rounded-full transition-colors flex items-center shadow"
            >
              <HelpCircle size={14} className="mr-1.5 opacity-70" />
              {prompt}
            </button>
          ))}
        </div>
      )}

      <div className="flex items-center space-x-2 border-t border-gray-700 pt-4">
        <input
          type="text"
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          onKeyPress={(e) => e.key === "Enter" && !isLoading && handleSendMessage()}
          placeholder="在此输入您的问题或指令..."
          className="flex-grow p-3 bg-gray-700 text-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 outline-none transition-shadow shadow-inner"
          disabled={isLoading}
        />
        <button
          onClick={handleSendMessage}
          disabled={isLoading}
          className="p-3 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg disabled:opacity-50 disabled:cursor-not-allowed transition-colors shadow-md focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:ring-offset-gray-800"
        >
          {isLoading ? (
            <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
          ) : (
            <Send size={20} />
          )}
        </button>
      </div>
    </div>
  );
};

export default ChatGPTSimulation;

